using MediatR;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.bankaccounts;
using SupplierCustomerManagement.Domain.Enums;
using System.ComponentModel;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.bankaccounts
{
    /// <summary>
    /// 获取账户关系枚举信息查询处理器
    /// </summary>
    public class GetAccountRelationshipEnumsQueryHandler : IRequestHandler<GetAccountRelationshipEnumsQuery, ApiResult<AccountRelationshipEnumsDto>>
    {
        private readonly ILogger<GetAccountRelationshipEnumsQueryHandler> _logger;

        public GetAccountRelationshipEnumsQueryHandler(ILogger<GetAccountRelationshipEnumsQueryHandler> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 处理获取账户关系枚举信息查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>枚举信息</returns>
        public async Task<ApiResult<AccountRelationshipEnumsDto>> Handle(GetAccountRelationshipEnumsQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取账户关系枚举信息");

                var result = new AccountRelationshipEnumsDto
                {
                    EntityTypes = GetEnumValues<EntityType>(),
                    AccountTypes = GetEnumValues<AccountType>(),
                    AccountProperties = GetEnumValues<AccountProperty>(),
                    AccountRelationshipTypes = GetEnumValues<AccountRelationshipType>()
                };

                _logger.LogInformation("成功获取账户关系枚举信息");

                return new ApiResult<AccountRelationshipEnumsDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "获取枚举信息成功",
                    data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取账户关系枚举信息时发生异常");
                
                return new ApiResult<AccountRelationshipEnumsDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取枚举信息时发生异常: {ex.Message}",
                    data = default
                };
            }
        }

        /// <summary>
        /// 获取枚举值列表
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns>枚举值列表</returns>
        private List<EnumValueDto> GetEnumValues<T>() where T : Enum
        {
            var enumValues = new List<EnumValueDto>();
            
            foreach (T enumValue in Enum.GetValues(typeof(T)))
            {
                enumValues.Add(new EnumValueDto
                {
                    Value = Convert.ToInt32(enumValue),
                    Name = enumValue.ToString(),
                    Description = GetEnumDescription(enumValue)
                });
            }

            return enumValues;
        }

        /// <summary>
        /// 获取枚举描述
        /// </summary>
        /// <param name="enumValue">枚举值</param>
        /// <returns>枚举描述</returns>
        private string GetEnumDescription(Enum enumValue)
        {
            var field = enumValue.GetType().GetField(enumValue.ToString());
            if (field != null)
            {
                var attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false)
                    .FirstOrDefault() as DescriptionAttribute;
                return attribute?.Description ?? enumValue.ToString();
            }
            return enumValue.ToString();
        }
    }
}